package com.example.dbsample.config.apollo;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import com.example.dbsample.model.dto.PlatformEnumConfig;
import com.example.dbsample.model.enums.PlatformEnum;
import com.example.dbsample.util.json.GsonUtil;
import com.example.dbsample.util.string.DynamicEnumUtil;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Component
@Slf4j
public class ApolloEnumConfigRefresh {
    private static final String ENUM_CONFIG = "enum.config";

    /**
     * 枚举只能动态新增，不能删
     */
    @Value("${enum.config:}")
    private String enumConfig;

    @PostConstruct
    public void init() {
        // 初始化
        addSamplePlatformEnum();
    }

    @ApolloConfigChangeListener(value = {"application"})
    public void refreshApolloConfig(ConfigChangeEvent event) {
        reloadExecutor(event);
    }

    private void reloadExecutor(ConfigChangeEvent event) {
        if(event.isChanged(ENUM_CONFIG)) {
            addSamplePlatformEnum();
        }
    }

    private void addSamplePlatformEnum() {
        List<PlatformEnumConfig> list = GsonUtil.fromJsonToType(enumConfig, new TypeToken<List<PlatformEnumConfig>>() {
        }.getType());

        if(CollectionUtils.isNotEmpty(list)) {
            list.forEach(e -> {
                PlatformEnum platformEnum = PlatformEnum.getEnumByCode(e.getCode());
                if(platformEnum != null) {
                    return;
                }
                DynamicEnumUtil.addEnum(PlatformEnum.class, e.getEnumName(),
                        new Class[]{String.class, String.class}, new Object[]{e.getCode(), e.getDesc()});
            });
        }
        for(PlatformEnum e : PlatformEnum.values()) {
            log.info(PlatformEnum.class.getSimpleName() + " " + e.name() + " " + e.getCode() + " " + e.getDesc());
        }
    }
}
